package com.marvels.loanapply.customer.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dragon.loan.dto.UserAgentDTO;
import com.dragon.loan.service.AcUserAgentMappingService;
import com.fintech.third.service.message.SmsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.sms.dao.PaymentCategorySmsMapper;
import com.marvels.loanapply.consum.LoanapplyConsumerDubboApi;
import com.marvels.loanapply.customer.dao.LoanCustomerDao;
import com.marvels.loanapply.customer.dto.LoanCustomerParamsDTO;
import com.marvels.loanapply.customer.dto.LoanCustomerResultDTO;
import com.marvels.loanapply.customer.dto.SendMsgDTO;
import com.marvels.loanapply.customer.dto.SmsTemplateNew;
import com.marvels.loanapply.customer.service.LoanCustomerService;
import com.marvels.loanapply.dao.CmFakeInfoDao;
import com.marvels.loanapply.dto.CmFakeInfoDTO;
import com.marvels.loanapply.dto.NotBorrowedDto;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class LoanCustomerServiceImpl implements LoanCustomerService {

	@Autowired
	private SmsService smsService;
	@Autowired
	private LoanCustomerDao loanCustomerDao;
	@Autowired
	private CmFakeInfoDao cmFakeInfoDao;
	@Autowired
	private LoanapplyConsumerDubboApi consumerDubboApi;
	@Autowired
	PaymentCategorySmsMapper paymentCategorySmsMapper;
	@Autowired
	AcUserAgentMappingService acUserAgentMappingService;
	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	
	@Override
	public List<LoanCustomerResultDTO> queryLoanCustomerList(LoanCustomerParamsDTO loanCustomerParamsDTO) throws MarvelsBusinessException {
		try {
			if(StrUtil.isNotEmpty(loanCustomerParamsDTO.getStatus())){
				if(loanCustomerParamsDTO.getStatus().equals("wrz")){
					loanCustomerParamsDTO.setNotVerify("true");
				}else if(loanCustomerParamsDTO.getStatus().equals("wxz")){
					loanCustomerParamsDTO.setNotDownload("true");
				}else if(loanCustomerParamsDTO.getStatus().equals("wsq")){
					loanCustomerParamsDTO.setNotApply("true");
				}else{
					loanCustomerParamsDTO.setStatusList(Arrays.asList(loanCustomerParamsDTO.getStatus().split(",")));
				}
			}
			PageHelper.startPage(loanCustomerParamsDTO.getPageNo(), loanCustomerParamsDTO.getPageSize());

			List<LoanCustomerResultDTO> customerList = loanCustomerDao.queryLoanCustomerList(loanCustomerParamsDTO);
			for (LoanCustomerResultDTO loanCustomerResultDTO : customerList) {
				UserAgentDTO userAgentDTO = acUserAgentMappingService.dealUserAgent(loanCustomerResultDTO.getUserAgent());
				loanCustomerResultDTO.setDevice(userAgentDTO == null ? "未知" : 
					StrUtil.format("设备：{}，浏览器：{}", userAgentDTO.getDevice(), userAgentDTO.getBrowser()));
			}
			return customerList;
		} catch (Exception e) {
			throw new MarvelsBusinessException(e);
		}
	}
	
	
	
	@Override
	public List<NotBorrowedDto> selectNotBorrowedList(LoanCustomerParamsDTO  dto) {
		try {
			PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
			Map<String,Object>  map= new HashMap<>();
			if(StringUtils.isNotBlank(dto.getStartDate()) && 
					StringUtils.isNotBlank(dto.getEndDate())) {
				map.put("startDate", dto.getStartDate()+" 00:00:00");
				map.put("endDate", dto.getEndDate()+" 23:59:59");
			}
			return loanCustomerDao.selectNotBorrowedList(map);
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}



	@Override
	public List<NotBorrowedDto> selectVerifyNotBorrowedList(LoanCustomerParamsDTO  dto) {
		try {
			PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
			Map<String,Object>  map= new HashMap<>();
			if(StringUtils.isNotBlank(dto.getStartDate()) && 
					StringUtils.isNotBlank(dto.getEndDate())) {
				map.put("startDate", dto.getStartDate()+" 00:00:00");
				map.put("endDate", dto.getEndDate()+" 23:59:59");
			}
			return loanCustomerDao.selectVerifyNotBorrowedList(map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询通过后未借款失败",e);
			return new ArrayList<>();
		}
	}



	@Override
	public HSSFWorkbook downloadCustomerListExcel(LoanCustomerParamsDTO loanCustomerParamsDTO,HttpServletRequest request, HttpServletResponse response) throws MarvelsBusinessException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/vnd.ms-excel");
		if(StrUtil.isNotEmpty(loanCustomerParamsDTO.getStatus())){
			if(loanCustomerParamsDTO.getStatus().equals("wrz")){
				loanCustomerParamsDTO.setNotVerify("true");
			}else if(loanCustomerParamsDTO.getStatus().equals("wxz")){
				loanCustomerParamsDTO.setNotDownload("true");
			}else if(loanCustomerParamsDTO.getStatus().equals("wsq")){
				loanCustomerParamsDTO.setNotApply("true");
			}else{
				loanCustomerParamsDTO.setStatusList(Arrays.asList(loanCustomerParamsDTO.getStatus().split(",")));
			}
		}
		if(StrUtil.isNotEmpty(loanCustomerParamsDTO.getDateRange())){
			String [] date = loanCustomerParamsDTO.getDateRange().split(" - ");
			loanCustomerParamsDTO.setStartRegisterDate(date[0].trim());
			loanCustomerParamsDTO.setEndRegisterDate(date[1].trim());
		}
		List<LoanCustomerResultDTO> list = loanCustomerDao.queryLoanCustomerList(loanCustomerParamsDTO);
		HSSFWorkbook workbook  = getCustomerListExcel(list);
		return workbook;
	}

	public HSSFWorkbook getCustomerListExcel(List<LoanCustomerResultDTO> list) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("用户列表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("用户ID");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("手机号码");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("来源");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("设备");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("申请额度");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("审批额度");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("发送短信次数");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("申请借款次数");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("注册时间");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("标签");
		cell.setCellStyle(style);

		Map<String, String> mapping = new HashMap<String, String>();
		mapping.put("wxz", "未下载");
		mapping.put("wrz", "未认证");
		mapping.put("wsq", "已认证未申请");
		mapping.put("K00,K01", "申请中");
		mapping.put("Z00,Z01,K02", "审核中");
		mapping.put("ZR0,SR0,CR0,SR4", "审核拒绝");
		mapping.put("P04", "签约中");
		mapping.put("F01,P05,F03", "待放款");
		mapping.put("F81","取消放款");
		mapping.put("D01", "待还款");
		mapping.put("A00,A01", "结清");
		
		List<LoanCustomerResultDTO> datas = list;
		if (datas != null && datas.size() > 0) {
			for (int i = 0; i < datas.size(); i++) {
				LoanCustomerResultDTO loanCustomerResult = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(check(loanCustomerResult.getUserId() + ""));
				row.createCell(1).setCellValue(check(loanCustomerResult.getUserName() + ""));
				row.createCell(2).setCellValue(check(loanCustomerResult.getMobileNum() + ""));
				row.createCell(3).setCellValue(check(loanCustomerResult.getSource() + ""));
				row.createCell(4).setCellValue(check(loanCustomerResult.getDevice() + ""));
				row.createCell(5).setCellValue(check(loanCustomerResult.getApplyMoney() + ""));
				row.createCell(6).setCellValue(check(loanCustomerResult.getLoanMoneyAct() + ""));
				row.createCell(7).setCellValue(check(loanCustomerResult.getSendMsgCount() + ""));
				row.createCell(8).setCellValue(check(loanCustomerResult.getLoanNumber() + ""));
				row.createCell(9).setCellValue(check(DateUtil.formatDateTime(loanCustomerResult.getRegisterDate())));
				for (Map.Entry<String, String> entry : mapping.entrySet()) {
					if(entry.getKey().contains(loanCustomerResult.getStatus())){
						row.createCell(10).setCellValue(check(entry.getValue() + ""));
					}
				}
				String flag = "无";
				if(StrUtil.equals(loanCustomerResult.getRenewFlag(), "0")){
					flag = "结清未续借";
				}
				if(StrUtil.equals(loanCustomerResult.getRenewFlag(), "1")){
					flag = "结清已续借";
				}
				row.createCell(11).setCellValue(flag);
				for (int j = 0; j < 10; j++) {
					row.getCell(j).setCellStyle(style2);
				}
			}
		}
		return wb;
	}

	public String check(String row) {
		if (row == null) {
			row = "";
		} else if ("null".equals(row)) {
			row = "";
		}
		return row;
	}


	@Override
	public Boolean sendMsg(LoanCustomerParamsDTO loanCustomerParamsDTO) throws MarvelsBusinessException {
		Boolean result = false;
		if (StrUtil.isNotBlank(loanCustomerParamsDTO.getUserIds())) {
			String[] userArray = loanCustomerParamsDTO.getUserIds().split(",");
			for (String userId : userArray) {
				if (StrUtil.isNotEmpty(userId)) {
					String mobileNo = loanCustomerDao.getMobileByUserId(userId);
					if (StrUtil.isNotEmpty(mobileNo)) {
						if (loanCustomerParamsDTO.getSmsCategory().equals("0")) {
							SendMsgDTO sendMsgDTO = new SendMsgDTO();
							sendMsgDTO.setTemplateName("userListSendMsg");
							sendMsgDTO.setMobielNo(mobileNo);
							boolean sendResult = consumerDubboApi.sendMsg(sendMsgDTO);
							if (sendResult) {
								loanCustomerDao.updateSendMsgCountByUserId(userId);
							}
						} else {
							net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
							jsonObject.put("template_id", loanCustomerParamsDTO.getSmsCategory());
							jsonObject.put("src", "management_list");
							jsonObject.put("phone", mobileNo);
							jsonObject.put("create_time", DateUtils.getDateYYYY_MM_DD_HH_MM_SS(new Date()));
							String platformName = ServerProperties.getValue(configPropertiesPath,
									"application.properties", "platform.name");
							jsonObject.put("paltName", platformName);
							smsService.sendSms(jsonObject);
						}
					}
				}
			}

			result = true;
		}
		return result;
	}


	@Override
	public LoanCustomerResultDTO getLoanCustomerInfo(LoanCustomerParamsDTO loanCustomerParamsDTO)
			throws MarvelsBusinessException {
		return loanCustomerDao.getLoanCustomerInfo(loanCustomerParamsDTO);
	}
	@Override
	public PageInfo<CmFakeInfoDTO> getCmFakeInfoList(Integer pageNo,Integer pageSize, String userName, String mobile) throws MarvelsBusinessException{
		if(StringUtils.isNotBlank(userName)){
			userName = userName.trim().replaceAll(" ", "");
		}
		if(StringUtils.isNotBlank(mobile)){
			mobile = mobile.trim().replaceAll(" ", "");
		}
		PageHelper.startPage((pageNo==null||pageNo<0)?1:pageNo, (pageSize==null||pageSize<0)?10:pageSize);
		List<CmFakeInfoDTO> list  = cmFakeInfoDao.selectCmFakeInfoList(userName, mobile);
		PageInfo<CmFakeInfoDTO> pageInfo = new PageInfo<CmFakeInfoDTO>(list);
		return pageInfo;
	}
	
	@Override
	public int updateCmFakeInfoStatus(CmFakeInfoDTO dto){
		int count = 0;
		CmFakeInfoDTO info = cmFakeInfoDao.selectCmFakeInfoInfo(dto);
		if (info!=null) {
			count = cmFakeInfoDao.updateCmFakeInfoStatus(dto);
		}else{
			count = cmFakeInfoDao.insert(dto);
		}
		return count ;
	}
	
	public HSSFWorkbook getNotBorrowedListExcel(List<NotBorrowedDto> list) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("未借款用户列表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("手机号");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("短信次数");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("注册时间");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("借款次数");
		cell.setCellStyle(style);
		
		List<NotBorrowedDto> datas = list;
		if (datas != null && datas.size() > 0) {
			for (int i = 0; i < datas.size(); i++) {
				NotBorrowedDto dto = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(check(dto.getRealName() + ""));
				row.createCell(1).setCellValue(check(dto.getMobile() + ""));
				row.createCell(2).setCellValue(check(dto.getSendSmsCount() + ""));
				row.createCell(3).setCellValue(check(dto.getRegTime() + ""));
				row.createCell(4).setCellValue(check(dto.getLoanCount() + ""));
		
			}
		}
		return wb;
	}
	
	
	@Override
	public List<NotBorrowedDto> selectNotBorrowedListWithoutPagesub(LoanCustomerParamsDTO  dto) {
		try {
			//PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
			Map<String,Object>  map= new HashMap<>();
			if(StringUtils.isNotBlank(dto.getStartDate()) && 
					StringUtils.isNotBlank(dto.getEndDate())) {
				map.put("startDate", dto.getStartDate()+" 00:00:00");
				map.put("endDate", dto.getEndDate()+" 23:59:59");
			}
			return loanCustomerDao.selectNotBorrowedList(map);
		} catch (Exception e) {
			return new ArrayList<>();
		}
	}



	@Override
	public List<NotBorrowedDto> selectVerifyNotBorrowedListWithoutPagesub(LoanCustomerParamsDTO  dto) {
		try {
			//PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
			Map<String,Object>  map= new HashMap<>();
			if(StringUtils.isNotBlank(dto.getStartDate()) && 
					StringUtils.isNotBlank(dto.getEndDate())) {
				map.put("startDate", dto.getStartDate()+" 00:00:00");
				map.put("endDate", dto.getEndDate()+" 23:59:59");
			}
			return loanCustomerDao.selectVerifyNotBorrowedList(map);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("查询通过后未借款失败",e);
			return new ArrayList<>();
		}
	}

	public void sendNotBorrowedMsg(String mobileList) {
		MarvelsLogUtil.getInstance().info("手机号列表,mobileList="+mobileList);
		if(StringUtils.isNotBlank(mobileList)) {
			String[] mobileArry = mobileList.split(",");
			if(mobileArry != null && mobileArry.length > 0){
				for(String mobile : mobileArry) {
					if(StringUtils.isBlank(mobile))
						continue;
					//发短信
					
				}
			}
		}
	}



	@Override
	public SmsTemplateNew getSmsTemplateNew() throws MarvelsBusinessException {
		SendMsgDTO sendMsgDTO = new SendMsgDTO();
		sendMsgDTO.setTemplateName("userListSendMsg");
		SmsTemplateNew smsTemplateNew = consumerDubboApi.getSmsTemplateNew(sendMsgDTO);
		return smsTemplateNew;
	}



	@Override
	public void allowReEntry(LoanCustomerParamsDTO dto) {
		if(dto == null || dto.getIcNumber() == null){
			return;
		}
		loanCustomerDao.updateAcLoanApplyInfoStatus(dto.getIcNumber(), "30", "F81");
		loanCustomerDao.updateMcamLoanApplyInfoStatus(dto.getIcNumber(), "30", "F81");
	}



	@Override
	public String getSmsTemplate(long id) throws MarvelsBusinessException {
		String content= paymentCategorySmsMapper.selectSmsTemplate(id);
		return content;
	}

}
